package com.wakyde.demo;

import java.util.*;

public class KeyWordUtil {

    public static int minMatchTYpe = 1;
    public static int maxMatchType = 2;

    /**
     * 生成关键字map
     */
    public static Map generateKeyWordMap(Set<String> keyWordSet) {
        HashMap keyWordMap = new HashMap(keyWordSet.size());
        String key = null;
        Map nowMap = null;
        Map<String, String> newWorMap = null;
        Iterator<String> iterator = keyWordSet.iterator();
        while (iterator.hasNext()) {
            key = iterator.next();
            nowMap = keyWordMap;
            for (int i = 0; i < key.length(); i++) {
                char keyChar = key.charAt(i);
                Object wordMap = nowMap.get(keyChar);
                if (wordMap != null) {
                    nowMap = (Map) wordMap;
                } else {
                    newWorMap = new HashMap<>();
                    newWorMap.put("isEnd", "0");
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }

                if (i == key.length() - 1) {
                    nowMap.put("isEnd", "1");
                }
            }
        }
        return keyWordMap;
    }

    /**
     * 关键字过滤
     */
    public static int checkKeyWord(Map<String, String> keyWordMap, String txt, int beginIndex, int matchType) {
        boolean flag = false;
        int matchFlag = 0;
        char word = 0;
        Map nowMap = keyWordMap;
        for (int i = beginIndex; i < txt.length(); i++) {
            word = txt.charAt(i);
            nowMap = (Map) nowMap.get(word);
            if (nowMap != null) {
                matchFlag++;
                if ("1".equals(nowMap.get("isEnd"))) {
                    flag = true;
                    if (minMatchTYpe == matchType) {
                        break;
                    }
                }
            } else {
                break;
            }
        }
        if (matchFlag < 2 || !flag) {
            matchFlag = 0;
        }
        return matchFlag;
    }

    /**
     * 获取关键字
     */
    public static Set<String> getKeyWord(Set<String> keyWord, String txt, int matchType) {
        Map<String, String> keyWordMap = generateKeyWordMap(keyWord);
        Set<String> keyWordList = new HashSet<>();
        for (int i = 0; i < txt.length(); i++) {
            int length = checkKeyWord(keyWordMap, txt, i, matchType);
            if (length > 0) {
                keyWordList.add(txt.substring(i, i + length));
                i = i + length - 1;
            }
        }
        return keyWordList;
    }
}